<template>
	<view class="container">
		<!-- 顶部信息栏 -->
		<view class="top-info">
			<view class="order-info">
				<view class="order-num">订单号：{{orderInfo.orderNumber}}</view>
				<view class="order-status">{{statusText}}</view>
			</view>
		</view>
		
		<!-- 地图区域 -->
		<view class="map-container">
			<map 
				id="myMap"
				class="map"
				:latitude="location.latitude" 
				:longitude="location.longitude"
				:markers="markers"
				:polyline="polyline"
				scale="14"
				show-location
			></map>
		</view>
		
		<!-- 乘客信息区域 -->
		<view class="passenger-info-container">
			<!-- 路线信息 -->
			<view class="route-info">
				<view class="route-item">
					<view class="route-dot pickup"></view>
					<view class="route-text">
						<view class="route-label">接乘客</view>
						<view class="route-address">{{orderInfo.pickupAddress}}</view>
					</view>
					<view class="route-distance">{{orderInfo.pickupDistance}}公里</view>
				</view>
				<view class="route-line"></view>
				<view class="route-item">
					<view class="route-dot dropoff"></view>
					<view class="route-text">
						<view class="route-label">目的地</view>
						<view class="route-address">{{orderInfo.destinationAddress}}</view>
					</view>
					<view class="route-distance">{{orderInfo.totalDistance}}公里</view>
				</view>
			</view>
			
			<!-- 乘客详细信息 -->
			<view class="passenger-detail">
				<view class="passenger-avatar">
					<image src="/static/avatar-default.png" mode="aspectFill"></image>
				</view>
				<view class="passenger-info">
					<view class="passenger-name">{{orderInfo.passengerName}}</view>
					<view class="passenger-rating">
						<text class="rating-text">乘客手机号 {{orderInfo.passengerPhone}}</text>
					</view>
				</view>
				<view class="contact-btn" @tap="callPassenger">
					<image src="/static/phone-icon.png" mode="aspectFit"></image>
				</view>
			</view>
			
			<!-- 订单状态与操作区域 -->
			<view class="action-container">
				<view class="action-time" v-if="isPickingUp">
					<text class="time-label">预计到达时间</text>
					<text class="time-value">{{orderInfo.estimatedArrivalTime}}分钟</text>
				</view>
				
				<view class="action-buttons">
					<button class="btn cancel-btn" @tap="contactUser" v-if="isPickingUp">联系乘客</button>
					<button class="btn arrive-btn" @tap="arrivePickup" v-if="isPickingUp">到达接乘点</button>
				</view>
				
				<!-- 验证码输入区域 -->
				<view class="verification-container" v-if="isArrived">
					<view class="verification-title">请乘客输入上车验证码</view>
					<view class="verification-input">
						<view class="code-display">
							<view class="code-box" v-for="(item, index) in 4" :key="index">
								<text v-if="verificationCode.length > index">{{verificationCode[index]}}</text>
							</view>
						</view>
					</view>
					<button class="btn confirm-btn" @tap="verifyAndConfirm" :disabled="verificationCode.length !== 4">
						确认乘客上车
					</button>
				</view>
				
				<!-- 数字键盘 -->
				<view class="keyboard-container" v-if="isArrived">
					<view class="keyboard-row" v-for="(row, rowIndex) in keyboard" :key="rowIndex">
						<view 
							class="keyboard-key" 
							v-for="key in row" 
							:key="key" 
							@tap="inputKey(key)"
						>
							{{key}}
						</view>
					</view>
					<view class="keyboard-row">
						<view class="keyboard-key empty"></view>
						<view class="keyboard-key" @tap="inputKey('0')">0</view>
						<view class="keyboard-key" @tap="deleteKey">删除</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '../../common/qqmap-wx-jssdk.js'
	import {getOrder,confirmStart,confirmEnd} from '@/request/order.js'
export default {
	data() {
		return {
			//定位api
			qqmapsdk:null,
			// 司机当前位置
			location: {
				latitude: null,
				longitude: null
			},
			//乘客位置
			userLocation:{
				latitude: null,
				longitude: null
			},
			//目的地地址
			endLocation:{
				latitude: null,
				longitude: null
			},
			// 地图标记点
			markers: [],
			// 路线
			polyline: [],
			// 状态：1-去接乘客，2-到达接乘点，3-乘客已上车，4-行程开始
			status: 1,
			getArrived:false,
			// 验证码相关
			verificationCode: '',
			correctCode: '1234', // 正确的验证码，实际应用中可能从服务器获取
			keyboard: [
				['1', '2', '3'],
				['4', '5', '6'],
				['7', '8', '9']
			],
			//乘客id
			passengerId:null,
			//司机id
			driverId:null,
			// 订单信息
			orderInfo: {
				
			}
		}
	},
	computed: {
		// 根据状态返回文本描述
		statusText() {
			const statusMap = {
				1: '前往接乘客',
				2: '已到达接乘点',
				3: '乘客已上车',
				4: '行程开始'
			}
			return statusMap[this.status] || '未知状态'
		},
		// 是否正在去接乘客
		isPickingUp() {
			return this.status === 1
		},
		// 是否已到达接乘点
		isArrived() {
			return this.status === 2
		},
	},
	onLoad() {
		// 初始化QQ地图SDK
		this.qqmapsdk = new QQMapWX({
			key: 'YYEBZ-FORCG-OEPQO-QE3GI-FW6SK-3JBTR'
		});
		this.getLocation();
		//与乘客建立连接
		//获取乘客的token
		const token = uni.getStorageSync('token');
		
		this.socket = uni.connectSocket({
			url: 'ws://127.0.0.1:8005/realTime',
			header: {
				'Token': token, //redis中存放用户信息的key值
				'sender_type': 'driver', //发送方类型
			},
			success: () => console.log('连接建立中...')
		});
		this.socket.onOpen(() => {
			console.log('WebSocket连接已打开');
		});
		
		let isPlanning = false;
		this.socket.onMessage(res => {
			console.log('收到消息:', res.data);
			const msg = JSON.parse(res.data)
			
			// 更新终点坐标
			this.endLat = parseFloat(msg.x / 1000000);
			this.endLng = parseFloat(msg.y / 1000000);
			if (!isPlanning) {
			        isPlanning = true;
			        setTimeout(() => {
			            this.planRoute();
			            isPlanning = false;
			        }, 1000); // 每秒最多调用一次
			}
			//this.scrollToBottom();
		});
		
		this.socket.onError(err => {
			console.error('WebSocket错误:', err);
		});
		
		this.socket.onClose(() => {
			console.log('WebSocket连接已关闭');
		});
		
		
		
		
		
		// this.simulateLocation();
	},
	// 组件销毁时停止监听
	onUnload() {
		// 清除定时器
		if (this.locationTimer) {
			clearInterval(this.locationTimer)
		}
		if (this.watchId) {
			uni.stopLocationUpdate();
			uni.offLocationChange();
		}
	},
	methods: {
		//实时获得司机的位置
		// 开始监听位置变化
		startLocationWatch() {
			uni.startLocationUpdate({
				success: () => {
					console.log('开始监听位置变化');
				},
				fail: (err) => {
					console.error('监听位置失败：', err);
				}
			});
			
			// 监听位置变化事件
			uni.onLocationChange((res) => {
				// 更新起点位置
				this.startLat = res.latitude;
				this.startLng = res.longitude;
				// 更新起点标记
				this.updateStartMarker();
				//当前位置发送给乘客
				// 检查是否到达目的地
				this.checkArrival();
				// 如果还没到达目的地，继续规划路线
				if (!this.getArrived) {
					this.plotRoute(res.latitude,res.longitude,this.userLocation.latitude,this.userLocation.longitude);
				}
			});
		},
		//发送当前位置
		sendMessages() {
			//重新计算坐标
			const x = this.startLat*1000000;
			const y = this.startLng*1000000;
			//发送消息
			if (this.socket) {
				const message = {
					id: this.driverId,
					style:"passenger",
					x: x,
					y: y
				};
				this.socket.send({
					data: JSON.stringify(message),
					success: () => {
						console.log('消息发送成功');
					},
					fail: (err) => {
						console.error('消息发送失败:', err);
					}
				});
			}else {
				console.error('WebSocket连接未建立');
			}
		},
		// 更新起点标记-随着用户的移动而移动
		updateStartMarker() {
			const startMarker = {
				id: 0,
				latitude: this.startLat,
				longitude: this.startLng,
				iconPath: '/static/car-icon.png',
				width: 40,
				height: 40,
				callout: {
					content: '当前位置',
					color: '#000000',
					fontSize: 14,
					borderRadius: 4,
					padding: 5,
					display: 'ALWAYS'
				}
			};
		},
		// 检查是否到达目的地
		checkArrival() {
			const distance = this.getMapDistance(
				this.startLat,
				this.startLng,
				this.userLocation.latitude,
				this.userLocation.longitude
			);
			// 如果距离小于50米，认为到达目的地
			if (distance < 100 && !this.getArrived) {
				this.getArrived = true;
				uni.showToast({
					title: '已到达目的地',
					icon: 'success',
					duration: 2000
				});
				// 停止位置更新
				uni.stopLocationUpdate();
				uni.offLocationChange();
			}
		},
		//获得司机当前位置
		getLocation() {
			// console.log("111222");
			//获得当前的位置信息
			uni.getLocation({
				type: "gcj02",
				success: (res) => {
					console.log(res);
					this.location.latitude = res.latitude;
					this.location.longitude = res.longitude;
					console.log(this.location.latitude, this.location.longitude,1234556789);
					this.getOrderInfo();
				},
				fail(err) {
					console.log(err);
				}
			})
		},
		getOrderInfo(){
			const userInfo = uni.getStorageSync('userInfo');
			this.driverId = userInfo.driverId;
			// console.log(driverId);
			getOrder(this.driverId ).then(res =>{
				console.log(res);
				const order = res.data[0];
				//找到乘客id
				this.passengerId = order.passengerId;
				//司机距离乘客的距离
				const pickupDistance = this.getMapDistance(this.location.latitude,this.location.longitude,order.startLat/ 1_000_000.0,order.startLng/ 1_000_000.0);
				//乘客到目的地的距离
				const totalDistance = this.getMapDistance(order.startLat/ 1_000_000.0,order.startLng/ 1_000_000.0,order.endLat/ 1_000_000.0,order.endLng/ 1_000_000.0);
				//司机到目的地的距离
				const mileage = parseFloat(pickupDistance) + parseFloat(totalDistance);
				//时间
				const totalTime = Math.round(mileage * 2);
				console.log(mileage,123132);
				
				this.userLocation = {
					latitude: order.startLat / 1_000_000.0,
					longitude: order.startLng/ 1_000_000.0
				};
				//目的地地址
				this.endLocation = {
					latitude: order.endLat/ 1_000_000.0,
					longitude: order.endLng/ 1_000_000.0
				};
				const phone = this.maskPhoneNumber(order.userphone);
				this.correctCode = this.getLastFourDigits(order.userphone);
				// const totalTime = Math.round(totalDistance * 2)
				console.log(order.userphone);
				this.orderInfo = {
					orderNumber : order.orderId,
					pickupAddress : order.startAddress,
					destinationAddress : order.endAddress,
					pickupDistance : pickupDistance,
					totalDistance : totalDistance,
					passengerName : order.username,
					estimatedArrivalTime : totalTime,
					passengerPhone : phone
				}
				this.initMap();
			})
		},
		//隐藏手机号部分
		maskPhoneNumber(phone) {
			if (phone.length !== 11) return "无效手机号"; // 确保手机号是11位
			return phone.substring(0, 2) + "*******" + phone.substring(9, 11);
		},
		// 获取手机号的后四位
		getLastFourDigits(phone) {
		  if (phone.length < 4) return "手机号长度不足"; // 确保手机号长度足够
		  return phone.substring(phone.length - 4); // 或者使用 phone.slice(-4)
		},
		// 初始化地图
		initMap() {
			// 创建司机位置标记
			const driverMarker = {
				id: 0,
				latitude: this.location.latitude,
				longitude: this.location.longitude,
				iconPath: '/static/car-icon.png',
				width: 60,
				height: 60
			}
			console.log(this.userLocation.latitude,this.userLocation.longitude,11111111111)
			// 创建接乘点标记
			const pickupMarker = {
				id: 1,
				latitude: this.userLocation.latitude,
				longitude: this.userLocation.longitude,
				iconPath: '/static/pickup-icon.png',
				width: 30,
				height: 30,
				callout: {
					content: '接乘点',
					color: '#000000',
					fontSize: 12,
					borderRadius: 5,
					bgColor: '#ffffff',
					padding: 5,
					display: 'ALWAYS'
				}
			}
			console.log(this.endLocation.latitude,this.endLocation.longitude,22222222222)
			// 创建目的地标记
			const destinationMarker = {
				id: 2,
				latitude: this.endLocation.latitude,
				longitude: this.endLocation.longitude,
				iconPath: '/static/destination-icon.png',
				width: 30,
				height: 30,
				callout: {
					content: '目的地',
					color: '#000000',
					fontSize: 12,
					borderRadius: 5,
					bgColor: '#ffffff',
					padding: 5,
					display: 'ALWAYS'
				}
			}
			this.markers = [driverMarker, pickupMarker, destinationMarker]
			this.plotRoute(this.location.latitude,this.location.longitude,this.userLocation.latitude,this.userLocation.longitude)
			// 开始监听位置变化
			this.startLocationWatch();
		},
		plotRoute(startLat,startLng,endLat,endLng){
			//使用定位api，这里不需要再次初始化qqmapsdk，因为已经在onLoad中初始化过了
			
			// 检查坐标是否有效
			if(!startLat || !startLng || !endLat || !endLng) {
				console.error('坐标无效，无法规划路线', startLat, startLng, endLat, endLng);
				return;
			}
			console.log('规划路线起点:', startLat, startLng);
			console.log('规划路线终点:', endLat, endLng);
			
			// 创建路线
			this.qqmapsdk.direction({
				mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
				//from参数不填默认当前地址
				from: `${startLat},${startLng}`,
				to: `${endLat},${endLng}`,
				success: (res) => {
					console.log('路线规划成功:', res);
					if(!res.result || !res.result.routes || !res.result.routes[0] || !res.result.routes[0].polyline) {
						console.error('路线数据格式不正确');
						return;
					}
					
					const ret = res;
					const coors = ret.result.routes[0].polyline;
					const pl = [];
					
					//坐标解压（返回的点串坐标，通过前向差分进行压缩）
					const kr = 1000000;
					for (let i = 2; i < coors.length; i++) {
						coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
					}
					
					//将解压后的坐标放入点串数组pl中
					for (let i = 0; i < coors.length; i += 2) {
						pl.push({
							latitude: coors[i],
							longitude: coors[i + 1]
						})
					}
					
					console.log('解压后的路线点数:', pl.length);
					
					// 确保路线点数组不为空
					if(pl.length > 0) {
						// 更新路线数据
						this.polyline = [{
							points: pl,
							color: '#009a00dd',
							width: 10,
							arrowLine: true // 显示箭头
						}];
						console.log('路线已更新');
					} else {
						console.error('路线点数组为空');
					}
				},
				fail: (error) => {
					console.error('路线规划失败:', error);
				},
				complete: (res) => {
					console.log('路线规划完成');
				}
			});
		},
		// 拨打乘客电话
		callPassenger() {
			uni.makePhoneCall({
				phoneNumber: this.orderInfo.passengerPhone,
				success: () => {
					console.log('拨打电话成功')
				},
				fail: (err) => {
					console.error('拨打电话失败', err)
					uni.showToast({
						title: '拨打电话失败',
						icon: 'none'
					})
				}
			})
		},
		// 联系乘客
		contactUser() {
			uni.navigateTo({
				url: `/pages/contactUser/contactUser?passengerId=${this.passengerId}`
			});
		},
		
		// 到达接乘点
		arrivePickup() {
			this.status = 2;
			uni.showToast({
				title: '已到达接乘点',
				icon: 'none'
			})
			
			// 清除位置模拟
			if (this.locationTimer) {
				clearInterval(this.locationTimer)
			}
			
		},
		
		// 验证码相关方法
		inputKey(key) {
			if (this.verificationCode.length < 4) {
				this.verificationCode += key
			}
		},
		
		deleteKey() {
			if (this.verificationCode.length > 0) {
				this.verificationCode = this.verificationCode.slice(0, -1)
			}
		},
		
		verifyAndConfirm() {
			if (this.verificationCode === this.correctCode) {
				this.status = 3
				this.verificationCode = ''
				console.log(this.driverId,23124144)
				confirmStart(this.driverId).then(res =>{
					console.log(res,11111111111111111)
					uni.showToast({
						title: '验证码正确，已确认乘客上车',
						icon: 'none'
					})
				}).catch(err =>{
					console.log(err);
				})
				
				this.status = 4
				uni.showToast({
					title: '行程开始',
					icon: 'none'
				});
				// 导航到行程页面
				setTimeout(() => {
					uni.navigateTo({
						 url: `/pages/goEnd/goEnd?startLat=${this.userLocation.latitude}&startLng=${this.userLocation.longitude}&endLat=${this.endLocation.latitude}&endLng=${this.endLocation.longitude}`
					})
				}, 1500);
			} else {
				uni.showToast({
					title: '验证码错误，请重新输入',
					icon: 'none'
				})
				this.verificationCode = ''
			}
		},
		
		//进行经纬度转换为距离的计算
		Rad(d) {
			return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
		},
		
		/*
		 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
		 默认单位km
		*/
		getMapDistance(lat1, lng1, lat2, lng2) {
			// console.log("in getMap")
			// console.log(lat1)
			var radLat1 = this.Rad(lat1);
			var radLat2 = this.Rad(lat2);
			var a = radLat1 - radLat2;
			var b = this.Rad(lng1) - this.Rad(lng2);
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
				Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137; // EARTH_RADIUS;
			s = Math.round(s * 10000) / 10000; //输出为公里
			s = s.toFixed(1);//保留一位小数
			// console.log(s,11111111111111111111111111111);
			return s;
		},
	},
	
}
</script>

<style>
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #f8f8f8;
}

/* 顶部信息栏 */
.top-info {
	background-color: #1B6EF3;
	color: #ffffff;
	padding: 20rpx 30rpx;
}

.order-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.order-num {
	font-size: 28rpx;
}

.order-status {
	font-size: 32rpx;
	font-weight: bold;
}

/* 地图区域 */
.map-container {
	height: 50vh;
	width: 100%;
}

.map {
	width: 100%;
	height: 100%;
}

/* 乘客信息区域 */
.passenger-info-container {
	flex: 1;
	background-color: #ffffff;
	border-radius: 20rpx 20rpx 0 0;
	margin-top: -20rpx;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 路线信息 */
.route-info {
	padding-bottom: 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

.route-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	position: relative;
}

.route-dot {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.route-dot.pickup {
	background-color: #1B6EF3;
}

.route-dot.dropoff {
	background-color: #FF6B00;
}

.route-text {
	flex: 1;
}

.route-label {
	font-size: 28rpx;
	color: #666;
}

.route-address {
	font-size: 32rpx;
	color: #333;
	margin-top: 4rpx;
}

.route-distance {
	font-size: 28rpx;
	color: #999;
}

.route-line {
	width: 2rpx;
	height: 40rpx;
	background-color: #ddd;
	margin-left: 10rpx;
	margin-bottom: 20rpx;
}

/* 乘客详细信息 */
.passenger-detail {
	display: flex;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.passenger-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	overflow: hidden;
	margin-right: 20rpx;
}

.passenger-avatar image {
	width: 100%;
	height: 100%;
}

.passenger-info {
	flex: 1;
}

.passenger-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.passenger-rating {
	display: flex;
	align-items: center;
	margin-top: 8rpx;
}

.rating-text {
	font-size: 28rpx;
	color: #666;
	margin-right: 10rpx;
}

.rating-star {
	font-size: 28rpx;
	color: #FF9500;
}

.contact-btn {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: #f2f8ff;
	display: flex;
	justify-content: center;
	align-items: center;
}

.contact-btn image {
	width: 40rpx;
	height: 40rpx;
}

/* 订单状态与操作区域 */
.action-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	padding-top: 30rpx;
}

.action-time {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.time-label {
	font-size: 28rpx;
	color: #666;
}

.time-value {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
}

.action-buttons {
	display: flex;
	justify-content: space-between;
}

.btn {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	border-radius: 45rpx;
	font-size: 32rpx;
	margin: 0 10rpx;
}

.cancel-btn {
	background-color: #f8f8f8;
	color: #666;
}

.arrive-btn {
	background-color: #1B6EF3;
	color: #fff;
}

.confirm-btn {
	background-color: #FF6B00;
	color: #fff;
}

.begin-btn {
	background-color: #00CC66;
	color: #fff;
}

/* 验证码输入区域 */
.verification-container {
	margin-top: 30rpx;
	padding: 20rpx;
	border-radius: 10rpx;
	background-color: #f9f9f9;
}

.verification-title {
	font-size: 28rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 20rpx;
	color: #333;
}

.verification-input {
	display: flex;
	justify-content: center;
	margin-bottom: 20rpx;
}

.code-display {
	display: flex;
	justify-content: center;
}

.code-box {
	width: 100rpx;
	height: 100rpx;
	border: 2rpx solid #ddd;
	border-radius: 10rpx;
	margin: 0 10rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 40rpx;
	font-weight: bold;
	background-color: white;
}

/* 数字键盘 */
.keyboard-container {
	margin-top: 20rpx;
	padding: 20rpx;
	background-color: #f0f0f0;
	border-radius: 10rpx;
}

.keyboard-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 15rpx;
}

.keyboard-key {
	width: 32%;
	height: 100rpx;
	background-color: white;
	border-radius: 10rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 36rpx;
	font-weight: bold;
	box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
}

.keyboard-key.empty {
	background-color: transparent;
	box-shadow: none;
}
</style>